import zipfile
import os
from zipfile import *

# Extract CSS from the epub file
def extractCss(filename):
    fin = ZipFile(filename, 'r')
    fout = ZipFile('temp.zip', 'w')
    info = None

    for tempInfo in fin.infolist():
        buff = fin.read(tempInfo.filename)
        if tempInfo.filename.find(".css") != -1:
            info = tempInfo
            continue

        fout.writestr(tempInfo, buff)

    fin.extract(info)

    fin.close()
    fout.close()
    return (info.filename, 'temp.zip')

# Do stuff on it. 
def inspectCss(filename):
    fin = open(filename, 'r')
    fout = open('temp.tmp', 'w')

    for line in fin:
        if (line.find('cnepub') != -1):
            continue
        fout.write(line+'\n')

    os.remove(filename)
    os.rename('temp.tmp', filename)

# Pack it back to epub
def packCss(zipFile, cssFile):
    zFile = ZipFile(zipFile, 'a')
    zFile.write(cssFile, cssFile)
    zFile.close()

# Main invocation
def process(zipFile):
    (cssName, newZipName) = extractCss(zipFile)
    inspectCss(cssName)
    packCss(newZipName, cssName)
    os.remove(cssName)
    os.remove(zipFile)
    os.rename(newZipName, zipFile)

# Walk through the whole dir, find all epub files, and process them.
for r,d,f in os.walk("/cygdrive/c/Users/RainG/Calibre Library - Copy"):
    for files in f:
        if files.endswith(".epub"):
             process(os.path.join(r,files))
             print "Processing %s" % os.path.join(r,files)
